package com.sniper.utils;

import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MapUtil {

    public static Map<String, String> sortTreeMapByKey(Map<String, String> oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, String> sortedMap = new TreeMap<>((key1, key2) -> {

            int intKey1, intKey2;
            try {
                intKey1 = getInt(key1);
                intKey2 = getInt(key2);
            } catch (Exception e) {
                intKey1 = 0;
                intKey2 = 0;
            }
            return intKey1 - intKey2;
        });
        sortedMap.putAll(oriMap);
        return sortedMap;
    }

    private static int getInt(String str) {
        int i = 0;
        try {
            Pattern p = Pattern.compile("^\\d+");
            Matcher m = p.matcher(str);
            if (m.find()) {
                i = Integer.parseInt(m.group());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return i;
    }

    public static Map<String, String> sortLinkedHashMapByValue(
            Map<String, String> oriMap) {
        Map<String, String> sortedMap = new LinkedHashMap<>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Entry<String, String>> entryList = new ArrayList<>(
                    oriMap.entrySet());
            entryList.sort((entry1, entry2) -> {
                int value1 = 0, value2 = 0;
                try {
                    value1 = getInt(entry1.getValue());
                    value2 = getInt(entry2.getValue());
                } catch (NumberFormatException e) {
                    value1 = 0;
                    value2 = 0;
                }
                return value2 - value1;
            });
            Iterator<Entry<String, String>> iter = entryList.iterator();
            Entry<String, String> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }

    /**
     * url参数
     *
     * @param params
     * @return
     */
    public static String mapToUrlParams(Map<String, String> params, String spec) {
        StringBuilder urlParam = new StringBuilder();
        for (Entry<String, String> entry : params.entrySet()) {
            String name = entry.getKey();
            if (!"".equals(name)) {
                urlParam.append(spec).append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
        //去除第一个&
        return urlParam.toString().substring(1);
    }
}
